package zdream.utils;

/**
 * @author Zdream
 * @date 2023-12-14
 * @since 0.0.1
 */
public class MathUtils {
	/**
	 * 给定每个事件的概率 [0~1], 计算 N 个事件成功的概率.
	 *
	 * 比如有两个事件的概率 [0.4, 0.7], 那么两个事件中只有 1 个成功的概率是 0.54
	 * 那么返回的数组 results[1] = 0.54
	 */
	public static float[] probabilityOfCompositeRates(float[] rates) {
		int maxLevel = rates.length;
		float[] results = new float[rates.length + 1];

		int max = 1 << maxLevel;
		for (int i = 0; i < max; i++) {
			int remain = i;
			int level = 0;
			float rate = 1;
			for (int j = 0; j < maxLevel; j++) {
				int current = remain % 2;
				if (current == 1) {
					level++;
				}
				rate *= current == 1 ? rates[j] : 1 - rates[j];
				remain >>= 1;
			}
			results[level] += rate;
		}

		return results;
	}
}
